# encoding=utf-8
from Parents.Base.HTMLTestRunnerCN import HTMLTestRunner
from email.mime.text import MIMEText
import smtplib
import unittest
import time, os
from LBT.TestCase.LoginCase.welcome_case import welcome
from LBT.TestCase.LoginCase.login_case import login
from LBT.TestCase.StudentInfoCase.studentinfo_case import StudentInfo
from LBT.TestCase.StudentInfoCase.graduationstudent_case import GraduationStudent

# ==============邮件接收者=================
mailreceivers = ['1020834716@qq.com']
# ==============发送人邮箱=================ss
mail_host = 'smtp.163.com'
mail_port = '25'
mail_user = 'kaifengrenxiu@163.com'
mail_pass = 'woaiwojia1314'


# =============发邮件功能=================
def send_mail(mailreceivers, file_new):
    '''
    :param mailreceivers:接收人列表
    :param file_new:文件名
    :return:true或者false
    '''
    f = open(file_new, 'rb')
    mail_body = f.read()
    f.close()
    msg = MIMEText(mail_body, 'html', 'utf-8')
    msg['Subject'] = '自动化测试报告'
    msg['From'] = mail_user
    msg['To'] = ';'.join(mailreceivers)
    try:
        s = smtplib.SMTP()
        s.connect(mail_host, mail_port)
        s.login(mail_user, mail_pass)
        s.sendmail(mail_user, mailreceivers, msg.as_string())
        s.close()
        return True

    except Exception as e:
        print(str(e))
        return False


# ===================查找测试报告目录，生成测试报告==================
def new_report(testreport):
    lists = os.listdir(testreport)
    lists.sort(key=lambda fn: os.path.getatime(testreport + '\\' + fn))
    file_new = os.path.join(testreport, lists[-1])
    print(file_new)
    return file_new


if __name__ == "__main__":
    now = time.strftime("%Y-%m-%d %H_%M_%S")
    filename = './Result/report/' + now + "result.html"
    fp = open(filename, 'wb')
    '''
    otherDes = ''
    if TestCaseConfig.isShowTestCase and TestCaseConfig.isShowTestCaseDetail:
        for testcase in TestCaseConfig.TestCases:
            otherDes += "<br />" + testcase['className'] + ":" + testcase['classCase']
            for casedeteil in dict(testcase['caseDetail']).keys():
                otherDes += "<br />&nbsp;&nbsp;&nbsp;&nbsp;" + casedeteil + ":" + dict(testcase['caseDetail'])[
                    casedeteil]
    elif TestCaseConfig.isShowTestCase:
        for testcase in TestCaseConfig.TestCases:
            otherDes += "<br />" + testcase['className'] + ":" + testcase['classCase']
    '''
    # htmltestrunnercn仍然有一个展示--收起--展开的bug，后面再改吧！！！
    runner = HTMLTestRunner(stream=fp, title='乐贝通front自动化测试报告', description='环境 ：window 7 浏览器：firefox')
    '''三种加载测试用例的方式'''
    discover = unittest.defaultTestLoader.discover("./TestCase/", pattern='*_case.py')  # 遍历所有用例去执行无序
    runner.run(discover)

    '''
    suite=unittest.TestSuite()
    suite.addTest(StudentInfo('test_exportstudent'))   #分用例（方法），去执行，按用例（方法）排序
    suite.addTest(GraduationStudent('test_checkGraduastudent'))
    
    for i in range(10):
        suite.addTest(unittest.makeSuite(welcome)) #整个类一块执行，按类排序
        suite.addTest(unittest.makeSuite(login))
    runner.run(suite)
    '''


    fp.close()
    filepath = new_report('./Result/report/')
    if send_mail(mailreceivers, filepath):
        print('发送邮件成功')
    else:
        print("发送邮件失败")
